package wiki.xsx.service;

import wiki.xsx.config.Database;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @Descript
 * @Author xsx
 * @Date 2017/11/20
 */
public abstract class AbstractService implements DatabaseService{
    protected Database database;
    protected Connection connection;

    @Override
    public void init(Database database){
        this.database = database;
        try{
            if (connection==null||connection.isClosed()){
                System.setProperty("jdbc.drivers", this.database.getDriverClassName());
                Properties properties = new Properties();
                properties.put("user", this.database.getDbUserName());
                properties.put("password", this.database.getDbPassword());
                properties.put("remarksReporting", "true");
                this.connection = DriverManager.getConnection(this.database.getDbUrl(), properties);
            }
        }catch (SQLException e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getAllTableNames() {
        List<String> tableNames = new ArrayList<>();
        if ("ALL".equalsIgnoreCase(this.database.getTableNames())){
            this.queryAllTableNames(tableNames);
        }else{
            tableNames.addAll(Arrays.asList(this.database.getTableNames().split(",")));
        }
        return tableNames;
    }

    @Override
    public void queryAllTableNames(List<String> tableNames) {
        try{
            DatabaseMetaData metaData = this.connection.getMetaData();
            try(
                ResultSet result = metaData.getTables(this.database.getDbName(), this.database.getDbUserName().toUpperCase(), "%", new String[]{"TABLE"})
            ){
                while (result.next()){
                    tableNames.add(result.getString("TABLE_NAME"));
                }
            }
        }catch (SQLException e){
            throw new RuntimeException(e);
        }
    }
}
